<template>
    <view class="register">

        <view class="login-header">
            <view class="login-header-logo">
                <image src="/static/logo.png" mode="aspectFit"></image>
            </view>
        </view>

        <view class="login-form">
            <!-- 表单 -->
            <u-form :model="form" ref="formRef" :rules="rules" label-position="left" label-width="120rpx">
                <!-- 手机号 -->
                <u-form-item label="手机号" prop="phone">
                    <u-input v-model="form.phone" placeholder="请输入手机号">
                        <template #prefix>
                            <u-icon name="phone" size="32" color="#909399" class="input-icon"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 密码 -->
                <u-form-item label="密码" prop="password">
                    <u-input v-model="form.password" :type="isPasswordVisible ? 'text' : 'password'"
                        placeholder="请输入密码">
                        <template #prefix>
                            <u-icon name="lock" size="32" color="#909399" class="input-icon"></u-icon>
                        </template>
                        <template #suffix>
                            <u-icon :name="isPasswordVisible ? 'eye-fill' : 'eye'" size="32" color="#909399"
                                @click="togglePasswordVisibility"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 确认密码 -->
                <u-form-item label="确认密码" prop="confirmPassword">
                    <u-input v-model="form.confirmPassword" :type="isConfirmPasswordVisible ? 'text' : 'password'"
                        placeholder="请再次输入密码">
                        <template #prefix>
                            <u-icon name="lock" size="32" color="#909399" class="input-icon"></u-icon>
                        </template>
                        <template #suffix>
                            <u-icon :name="isConfirmPasswordVisible ? 'eye-fill' : 'eye'" size="32" color="#909399"
                                @click="toggleConfirmPasswordVisibility"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 角色选择 -->
                <u-form-item label="角色" prop="role">
                    <view class="picker" @click="showRoleSelector = true">
                        {{ selectedRoleLabel || '请选择角色' }}
                    </view>
                </u-form-item>

                <!-- 弹出选择器 -->
                <u-action-sheet :show="showRoleSelector" :actions="roles" title="请选择角色"
                    @close="showRoleSelector = false" @select="handleRoleSelect" key-name="label"></u-action-sheet>

            </u-form>

            <!-- 注册按钮 -->
            <u-button type="primary" @click="handleRegister" :loading="isLoading" class="login-button"
                :disabled="isLoading">
                注册
            </u-button>
        </view>
    </view>
</template>


<script setup>
import { ref, computed } from 'vue'
import { registerAPI } from '../../../API/auth/register'


// 修改1: 调整表单初始值
const form = ref({
    phone: '',
    password: '',
    confirmPassword: '',
    role: null // 初始值为null，确保触发必填验证
})

// 控制弹出层显示
const showRoleSelector = ref(false)

// 状态管理
const isLoading = ref(false)
const isPasswordVisible = ref(false)
const isConfirmPasswordVisible = ref(false)
const formRef = ref(null)

// 页面配置
const headerBg = {
    backgroundColor: '#007AFF'
}

// 可选角色列表
const roles = [
    { name: '老人', value: 'older' },
    { name: '家人', value: 'family' },
    { name: '医生', value: 'doctor' }
]



// 修改2: 调整角色选择处理逻辑
// 角色选择回调
const handleRoleSelect = (item) => {
    console.log(item);

    form.value.role = item.value // 存储角色value值
    showRoleSelector.value = false
}

// 修改3: 调整计算属性逻辑
// 当前选中的角色标签
const selectedRoleLabel = computed(() => {
    const selected = roles.find(r => r.value === form.value.role)
    return selected ? selected.name : '请选择角色'
})

// 切换密码可见性
const togglePasswordVisibility = () => {
    isPasswordVisible.value = !isPasswordVisible.value
}
const toggleConfirmPasswordVisibility = () => {
    isConfirmPasswordVisible.value = !isConfirmPasswordVisible.value
}

// 角色选择变化时触发
const onRoleChange = (index) => {
    console.log('角色选择索引:', index)
}

// 自定义密码一致性验证
const validatePasswordMatch = (rule, value, callback) => {
    if (value !== form.value.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

// 表单验证规则
const rules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '至少输入6个字符', trigger: 'blur' },
        // {
        //     pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,}$/,
        //     message: '至少包含大小写字母和数字',
        //     trigger: 'blur'
        // }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePasswordMatch, trigger: 'blur' }
    ],
    role: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change',
            // 添加自定义验证确保值有效
            validator: (rule, value, callback) => {
                if (!value || !roles.some(r => r.value === value)) {
                    callback(new Error('请选择有效角色'))
                } else {
                    callback()
                }
            }
        }
    ]
}

// 注册处理
const handleRegister = async () => {
    try {
        const valid = await formRef.value.validate()
        if (!valid) return


        const data = {
            phone: form.value.phone,
            password: form.value.password,
            role: form.value.role
        }
        isLoading.value = true

        const res = await registerAPI(data);
        if (res.code === 200) {
            uni.showToast({ title: '注册成功', icon: 'success' })
            setTimeout(() => {
                uni.navigateBack() // 返回上一页或跳转到登录页
            }, 1500)

        }

    } catch (error) {
        uni.showToast({ title: '注册失败，请重试', icon: 'none' })
    } finally {
        isLoading.value = false
    }
}
</script>


<style lang="scss" scoped>
.register {
    background-color: #f5f5f5;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.login-header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;

    .login-header-logo {
        width: 240rpx;
        height: 240rpx;

        image {
            width: 100%;
            height: 100%;
            border-radius: 16rpx;
        }
    }
}

.login-form {
    flex: 1;
    padding: 20rpx 40rpx;
    margin-top: 20rpx;
    background-color: #fff;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;
}

.input-icon {
    margin-right: 20rpx;
}

.login-button {
    margin-top: 40rpx;
}

.picker {
    font-size: 28rpx;
    color: #333;
    padding: 16rpx 0;
}
</style>